<?php
/**
 * Created by PhpStorm.
 * User: boye009
 * Date: 2016/3/17
 * Time: 9:58
 */

namespace Api\Domain;

use Bbs\Api\FilterKeyWordsApi;
use Bbs\Api\ForumAttachmentApi;
use Bbs\Api\ForumForumApi;
use Bbs\Api\ForumPostApi;
use Bbs\Api\ForumThreadApi;
use Bbs\Model\ForumAdmingroupModel;
use Bbs\Model\ForumPostModel;
use Shop\Api\FavoritesApi;
use Ucenter\Api\MemberApi;
use Ucenter\Api\MemberExpApi;

class ForumThreadDomain extends BaseDomain{

    protected $business_code = 'forumThread';

    protected $allowType = array("json", "rss", "html");

    /**
     * 假删除
     */
    public function delete(){

        $this->checkVersion(100);
        addLog("ForumThread/delete", $_GET, $_POST, $this->client_id . "调用论坛主题删除接口!");

        if(IS_POST){

            $tid = $this -> _post('tid',"",'缺少tid参数');
            $uid = $this -> _post('uid',"",'用户id缺失');

            $result = apiCall(ForumThreadApi::DELETE,array($tid,$uid));
            if($result['status']){
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }


    }

    public function getFavorites(){

        $this->checkVersion(100);
        addLog("ForumThread/favorites", $_GET, $_POST, $this->client_id . "调用分页查询主题帖接口!");

        if(IS_POST){

            $type = 2;//主题帖

            $uid = $this -> _post('uid',0,'用户id缺失');
            $page_no = $this -> _post('page_no',1);
            $page_size = $this -> _post('page_size',10);
            $img_num = $this -> _post('post.img_num',3);

            $page = array(
                'curpage'=>$page_no,
                'size'=>$page_size,
            );

            $map = array(
                'uid' => $uid,
                'type' => $type,
            );

            $result = apiCall(FavoritesApi::QUERY_THREAD_WITH_COUNT,array($map,$page));
            if($result['status']){

                foreach($result['info']['list'] as $k => $v){
                    $modnewposts = $v['modnewposts'];

                    $time = time() -> $v['dateline'];
                    $result['info']['list'][$k]['dateline_show'] = getDateInfo($time,$v['dateline']);

                    //取用户信息
                    $result['info']['list'][$k]['user_info'] = $this->getUserInfo($v['author_id']);

                    $map = array(
                        'tid' => $result['info']['list'][$k]['tid'],
                    );
                    $field = "aid,pid";
                    $res = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,$field));
                    if($res['status']){
                        $result['info']['list'][$k]['img'] = array();
                        $i = 0;
                        foreach($res['info'] as $v){
                            //判断附件所属帖子是否能显示（审核通过与否）
                            $post_info = apiCall(ForumPostApi::GET_INFO,array(array('pid'=>$v['pid'])));
                            if($post_info['status']){
                                if(is_null($post_info['info'])){
                                    continue;
                                }elseif($post_info['info']['status']==0 || ($post_info['info']['invisible']==0 && $modnewposts==1)){
                                    //删除的帖子和未通过审核的附件不显示
                                    continue;
                                }
                            }else{
                                continue;
                            }

                            array_push($result['info']['list'][$k]['img'],$v['aid']);
                            $i++;
                            if($i == $img_num){
                                break;
                            }
                        }
                    }else{
                        $this -> apiReturnErr($res['info']);
                    }
                }

                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    public function favorites(){

        $this->checkVersion(100);
        addLog("ForumThread/favorites", $_GET, $_POST, $this->client_id . "调用主题帖收藏接口!");

        if(IS_POST){

            $tid = $this -> _post('tid',-1,'缺少tid参数');
            $uid = $this -> _post('uid',-1,'缺少uid参数');
            $favorite_value = $this -> _post('favorite_value',-1,'缺少favorite_value参数');

            $type = 2;

            $map = array(
                'uid' => $uid,
                'favorite_id' => $tid,
                'type' => $type,
            );

            $result = apiCall(FavoritesApi::GET_INFO,array($map));
            if(!$result['status']){
                $this -> apiReturnErr($result['info']);
            }

            if($favorite_value == 1){
                if(!is_null($result['info'])){
                    //已经存在收藏信息
                    $this -> apiReturnErr('该收藏已存在!');
                }
                $map = array(
                    'tid' => $tid,
                );
                $result = apiCall(ForumThreadApi::GET_INFO,array($map));
                if(!$result['status']){
                    $this -> apiReturnErr($result['info']);
                }
                $favorite_content = json_encode($result['info']);

                $entity = array(
                    'uid' => $uid,
                    'type' => 2,
                    'favorite_id' => $tid,
                    'create_time' => time(),
                    'favorite_content' => $favorite_content,
                );
                $result = apiCall(FavoritesApi::ADD,array($entity));
                if($result['status']){
                    $this -> apiReturnSuc($result['info']);
                }else{
                    $this -> apiReturnErr($result['info']);
                }

            }else if($favorite_value == 0){
                if(is_null($result['info'])){
                    //不存在收藏信息
                    $this -> apiReturnErr('不存在该收藏信息!');
                }
                $id = $result['info']['id'];

                $map = array(
                    'id' => $id,
                );
                $result = apiCall(FavoritesApi::DELETE,array($map));
                if($result['status']){
                    $this -> apiReturnSuc('取消收藏成功！');
                }else{
                    $this -> apiReturnErr($result['info']);
                }

            }else{
                $this -> apiReturnErr('favorite_value参数错误');
            }

        }

    }

    public function detail(){

        $this->checkVersion(100);
        addLog("ForumThread/detail", $_GET, $_POST, $this->client_id . "调用论坛主题详情接口!");

        if(IS_POST){
            $uid = $this -> _post('uid','');
            $tid = $this -> _post('tid','','主题帖id缺失');

            if($tid == 'rrasj'){
                $tid = 6068;
            }else if($tid == 'fxphb'){
                $tid = 6067;
            }

            $map = array(
                'tid' => $tid,
            );
            $result = apiCall(ForumThreadApi::GET_INFO,array($map));
            if($result['status']){
                $modnewposts = $result['info']['modnewposts'];
                $result['info']['user_info'] = $this->getUserInfo($result['info']['author_id']);

                $field = "aid";
                $res = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,$field));
                if($res['status']){
                    $result['info']['img'] = array();
                    foreach($res['info'] as $v){
                        //判断附件所属帖子是否能显示（审核通过与否）
                        $post_info = apiCall(ForumPostApi::GET_INFO,array(array('pid'=>$v['pid'])));
                        if($post_info['status']){
                            if(is_null($post_info['info'])){
                                continue;
                            }elseif($post_info['info']['status']==0 || ($post_info['info']['invisible']==0 && $modnewposts==1)){
                                //删除的帖子和未通过审核的附件不显示
                                continue;
                            }
                        }else{
                            continue;
                        }
                        array_push($result['info']['img'],$v['aid']);
                    }
                }else{
                    $this -> apiReturnErr($res['info']);
                }

                $map = array(
                    'uid' => $uid,
                    'type' => 2,
                    'favorite_id' => $tid,
                );
                $result['info']['favorite'] = 0;
                if($uid !== ''){
                    $res = apiCall(FavoritesApi::GET_INFO,array($map));
                    if($res['status']){
                        if(!is_null($res['info'])){
                            $result['info']['favorite'] = 1;
                        }
                    }else{
                        $this -> apiReturnErr($res['info']);
                    }
                }
                $map = array(
                    'fid' => $result['info']['fid'],
                );
                $res = apiCall(ForumForumApi::GET_INFO,array($map));
                if($res['status']){
                    $result['info']['modnewposts'] = $res['info']['modnewposts'];
                }else{
                    $this -> apiReturnErr($res['info']);
                }
                $map = array(
                    'tid' => $tid,
                    'position' => 0,
                );
                $res = apiCall(ForumPostApi::GET_INFO,array($map));
                if($res['status']){
                    $result['info']['invisible'] = $res['info']['invisible'];
                }else{
                    $this -> apiReturnErr($res['info']);
                }

                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }



        }

    }

    public function query(){

        $this->checkVersion(100);
        addLog("ForumThread/query", $_GET, $_POST, $this->client_id . "调用论坛主题查询接口!");

        if(IS_POST){

            $fid = $this -> _post('fid',0);
            $stick = $this -> _post('stick',-1);
            $page_no = $this -> _post('page_no',1);
            $page_size = $this -> _post('page_size',10);
            $name = $this -> _post('name','');
            $img_num = $this -> _post('img_num',3);

            $page = array('curpage'=>$page_no,'size'=>$page_size);

            //查询论坛是否需要审核
            $modnewposts = 0;
            $result = apiCall(ForumForumApi::GET_INFO,array(array('fid'=>$fid)));
            if($result['status']){
                $modnewposts = $result['info']['modnewposts'];
            }

            $map = array(
                'itboye_forum_thread.status' => 1,//未被删除的
            );
            $map_invisible = "post.invisible='1' OR itboye_forum_forum.modnewposts='0'";
            if($fid !== 0){
                $map['itboye_forum_thread.fid'] = $fid;
            }
            if($stick == 0 || $stick == 1){
                $map['itboye_forum_thread.stick'] = $stick;
            }
            if($name !== ''){
                $map['itboye_forum_thread.subject'] = array('like','%'.$name.'%');
            }

            $order = "itboye_forum_thread.dateline desc";

            $result = apiCall(ForumThreadApi::QUERY_WITH_COUNT,array($map,$map_invisible,$page,$order));

            if($result['status']){
                foreach($result['info']['list'] as $k => $vo){
                    $time = time() - $vo['dateline'];
                    $result['info']['list'][$k]['dateline_show'] = getDateInfo($time,$vo['dateline']);

                    //取用户信息
                    $result['info']['list'][$k]['user_info'] = $this->getUserInfo($vo['author_id']);

                    $map = array(
                        'tid' => $result['info']['list'][$k]['tid'],
                    );
                    $field = "aid,pid";
                    $res = apiCall(ForumAttachmentApi::QUERY_NO_PAGING,array($map,false,$field));
                    if($res['status']){
                        $result['info']['list'][$k]['img'] = array();
                        $i = 0;
                        foreach($res['info'] as $v){
                            //判断附件所属帖子是否能显示（审核通过与否）
                            $post_info = apiCall(ForumPostApi::GET_INFO,array(array('pid'=>$v['pid'])));
                            if($post_info['status']){
                                if(is_null($post_info['info'])){
                                    continue;
                                }elseif($post_info['info']['status']==0 || ($post_info['info']['invisible']==0 && $modnewposts==1)){
                                    //删除的帖子和未通过审核的附件不显示
                                    continue;
                                }
                            }else{
                                continue;
                            }

                            array_push($result['info']['list'][$k]['img'],$v['aid']);
                            $i++;
                            if($i == $img_num){
                                break;
                            }
                        }
                    }else{
                        $this -> apiReturnErr($res['info']);
                    }
                }
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }


    public function add(){

        $this->checkVersion(100);

        addLog("ForumThread/add", $_GET, $_POST, $this->client_id . "调用论坛主题添加接口!");

        if(IS_POST){

            $fid = $this -> _post('fid',0,'版块id参数缺失');
            $typeid = $this -> _post('typeid',-1,'类型id参数缺失');
            $author = $this -> _post('author','','用户名参数缺失');
            $author_id = $this -> _post('author_id',0,'用户id参数缺失');
            $subject = $this -> _post('subject','','标题参数缺失');
            $message = $this -> _post('message','','主题帖内容参数缺失');
            $attachments = $this -> _post('attachments','');


            //关键词过滤
            $subject = $this->filter($subject);
            $message = $this->filter($message);


            //用户是否禁言验证
            $res = $this -> getUserInfo($author_id);
            //验证该用户是否在该板块
            if(isset($res['group']) && ($fid == $res['group']['fid'] || $fid == 0)){
                //验证是否被禁言
                if($res['group'][ForumAdmingroupModel::ALLOW_POST] == 0){
                    $this -> apiReturnErr("该用户无权限发帖");
                }
            }

            if($fid < 0 || $typeid < 0 || $author_id <0){
                $this -> apiReturnErr('参数错误');
            }
            $now = time();
            $ip = 0;
            if(!empty($_SERVER['REMOTE_ADDR'])){
                $ip = $_SERVER['REMOTE_ADDR'];
            }

            $thread_entity = array(
                'fid' => $fid,
                'typeid' => $typeid,
                'author' => $author,
                'author_id' => $author_id,
                'subject' => $subject,
                'dateline' => $now,
                'views' => 0,
                'replies' => 0,
                'digest' => 0,
                'stick' => 0,
                'status' => 1,
                'likes' => 0,
            );
            $post_entity = array(
                'author' => $author,
                'author_id' => $author_id,
                'subject' => $subject,
                'dateline' => $now,
                'message' => $message,
                'useip' => ip2long($ip),
                'invisible' => 0,//初始未通过审核
                'status' => 1,
                'comment' => 0,
                'position' => 0,
                'fid' => $fid,
            );


            $result = apiCall(ForumThreadApi::ADD_THREAD,array($thread_entity,$post_entity));
            if($result['status']){
                $tid = $result['info']['tid'];
                $pid = $result['info']['pid'];

                //添加附件
                if($attachments !== ""){
                    $aid = explode(',',$attachments);
                    $dataList = array();
                    $i = 0;
                    foreach($aid as $v){
                        $dataList[$i] = array(
                            'tid' => $tid,
                            'pid' => $pid,
                            'uid' => $author_id,
                            'aid' => $v,
                        );
                        $i++;
                    }
                    $result = apiCall(ForumAttachmentApi::ADD_ALL,array($dataList));
                }
                if($result['status']){
                    //改变版块中主题数量、帖子数量以及最后发表人
                    $result = apiCall(ForumForumApi::UPDATE,array($fid,$author,1));
                    if($result['status']){
                        //发布帖子+50分 +1经验
                        apiCall(MemberApi::RAISE_SCORE,array($author_id,50));
                        apiCall(MemberExpApi::EXP_INC,array($author_id,10));
                        $this -> apiReturnSuc($tid);
                    }else{
                        $this -> apiReturnErr($result['info']);
                    }

                }else{
                    $this -> apiReturnErr($result['info']);
                }

            }else{
                $this -> apiReturnErr($result['info']);
            }
        }

    }

    public function like(){

        $this->checkVersion(100);
        addLog("ForumThread/like", $_GET, $_POST, $this->client_id . "调用论坛主题点赞接口!");

        if(IS_POST){

            $tid = $this -> _post('tid',0,'主题帖id参数缺失');

            $map = array(
                'tid' => $tid,
            );
            $field = "likes";

            $result = apiCall(ForumThreadApi::SET_INC,array($map,$field));
            if($result['status']){
                $this -> apiReturnSuc('点赞成功!');
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    public function digest(){

        $this->checkVersion(100);
        addLog("ForumThread/digest", $_GET, $_POST, $this->client_id . "调用论坛主题帖加精接口!");

        if(IS_POST){

            $uid = $this -> _post('uid',0,'用户id缺失');
            $tid = $this -> _post('tid',0,'缺少主题id');
            $digest_value = $this -> _post('digest_value',-1,'缺少digest_value参数');

            if($digest_value != 0 && $digest_value != 1){
                $this -> apiReturnErr('digest_value参数错误');
            }

            $result = apiCall(ForumThreadApi::DIGEST,array($uid,$tid,$digest_value));
            if($result['status']){
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }

    //TODO 限制置顶主题个数
    public function stick(){

        $this->checkVersion(100);
        addLog("ForumThread/stick", $_GET, $_POST, $this->client_id . "调用论坛主题帖置顶接口!");

        if(IS_POST){
            $uid = $this -> _post('uid',0,'缺少uid参数');
            $tid = $this -> _post('tid',0,'缺少tid参数');
            $stick_value = $this -> _post('stick_value',-1,'缺少stick_value参数');

            if($stick_value != 0 && $stick_value != 1){
                $this -> apiReturnErr('stick_value参数错误');
            }

            $result = apiCall(ForumThreadApi::STICK,array($uid,$tid,$stick_value));
            if($result['status']){
                $this -> apiReturnSuc($result['info']);
            }else{
                $this -> apiReturnErr($result['info']);
            }

        }

    }
    /**
     * 查询用户信息
     */
    private function getUserInfo($uid){
        $result = apiCall('Api/BbsUserCenter/userInfo',array($uid),'Domain');
        if($result['status']){
            return $result['info'];
        }else{
            $this->apiReturnErr('查询用户信息失败');
        }
    }

    /**
     * 关键词过滤
     */
    private function filter($posts){
        $result = apiCall(FilterKeyWordsApi::FILTER,array($posts));
        return $result['info'];
    }

    /**
     * utf8-转unicode
     */
    public function unicode_encode($text){
        $str = json_encode($text);
        $str = str_replace("\"", "", $str);

        return $str;
    }

    /**
     * unicode-转utf8
     */
    public function unicode_decode($str){
        $str = "\"$str\"";
        $text = "{\"text\":".$str."}";
        $arr = json_decode($text,true);
        return $arr['text'];


    }

}